package com.ktjy;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RoutingQueueProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/T384");
        //创建连接对象
        Connection connection = factory.newConnection();
        //创建信道对象
        Channel channel = connection.createChannel();

        //定义交换机
        String exchangeName="routing_exchange";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT,true,false,false,null);
        //定义一个队列
        String fileQueue="file_queue";
        channel.queueDeclare(fileQueue,true,false,false,null);
        String dbQueue="db_queue";
        channel.queueDeclare(dbQueue,true,false,false,null);

        //3.绑定队列和交换机
        channel.queueBind(dbQueue,exchangeName,"error");

        channel.queueBind(fileQueue,exchangeName,"info");
        channel.queueBind(fileQueue,exchangeName,"warning");
        channel.queueBind(fileQueue,exchangeName,"error");

        //发信息
        String msg="hello world【error】";
        channel.basicPublish(exchangeName,"error",null,msg.getBytes());

        msg="hello world【info】";
        channel.basicPublish(exchangeName,"info",null,msg.getBytes());

        msg="hello world【warning】";
        channel.basicPublish(exchangeName,"warning",null,msg.getBytes());

        System.out.println("消息发送成功");

        //关闭信道和连接对象
        channel.close();
        connection.close();
    }
}
